Python Dictionary
π fun_with_python_dictionaries.md
β
π Fun with Python Dictionaries! π§ π₯β
Welcome to the world of Python Dictionaries β where curly braces {}
become treasure chests, and key-value pairs are your loot! βοΈπ°
A Dictionary in Python is like your magical backpack: unordered (so it might take a sec to find stuff), mutable (you can change whatβs inside), and indexed (but in a key-unique way).
In short:
π§³ Dictionary = HashTable from Java + Pythonβs charm + chaos of an unordered sock drawer.
1. π§Ύ Creating the Dictionaryβ
1.1. With Curly Braces β The OG Wayβ
Just slap some key-value pairs inside {}
like itβs a grocery list.
# an empty dictionary
Dict = {}
# a dictionary with 3 items
Dict = {
"Name": "sujit",
"Age": 30,
"Blog": "fossguru"
}
print(Dict)
π¨οΈ Output:
{'Age': 30, 'Name': 'sujit', 'Blog': 'fossguru'}
1.2. Using the dict()
Constructor β The Fancy Pants Wayβ
Why just write curly braces when you can summon dictionaries using dict()
? π©β¨
# Creating a Dictionary with dict() method
Dict = dict({1: 'Python', 2: 'Example'})
print(Dict)
# Creating a Dictionary with tuples
Dict = dict([(1, 'Python'), (2, 'Example')])
print(Dict)
# Notice that the keys are not the string literals
Dict = dict(firstName="sujit", lastName="karne", age=30)
print(Dict)
π¨οΈ Output:
{1: 'Python', 2: 'Example'}
{1: 'Python', 2: 'Example'}
{'firstName': 'sujit', 'lastName': 'karne', 'age': 30}
2. π Accessing the Values β Show Me the Lootβ
Two ways to get to your precious dictionary values:
Dict[key]
β Classic but may scream (KeyError
) if key is missing!Dict.get(key)
β Nicer, calmer, lets you provide a backup value.
Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}
print(Dict["name"])
print(Dict.get("age"))
print(Dict.get("country"))
print(Dict.get("country", "India"))
π¨οΈ Output:
sujit
30
None
India
3. π΅οΈββοΈ Is That Key Even There?β
Before opening a mystery box, make sure it exists. π§
3.1. key in Dict
β
Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}
if "name" in Dict:
print("name is present")
else:
print("name is not present")
π¨οΈ Output:
name is present
3.2. key not in Dict
β
Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}
if "country" not in Dict:
print("country is not present")
else:
print("country is present")
π¨οΈ Output:
country is not present
4. π οΈ Adding / Updating the Valuesβ
New name? Different country? Dictionaries donβt mind your identity crisis.
Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}
print(Dict["name"])
# Updating the name
Dict["name"] = "Alex"
print(Dict["name"])
# Updating the name with update() method
Dict.update({"name": "Brian"})
print(Dict["name"])
# Adding a new item - country
Dict.update({"country": "India"})
print(Dict["country"])
π¨οΈ Output:
sujit
Alex
Brian
India
5. π£ Deleting Dictionary Itemsβ
5.1. Using del
β The Nuclear Optionβ
Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}
print(Dict)
# Deleting the name
del Dict["name"]
print(Dict)
# Deleting the dictionary
del Dict
print(Dict)
π¨οΈ Output:
{'name': 'sujit', 'blog': 'fossguru', 'age': 30}
{'blog': 'fossguru', 'age': 30}
Traceback (most recent call last):
File "<string>", line 14, in <module>
NameError: name 'Dict' is not defined
5.2. pop()
β A Gentle Kick Outβ
Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}
print(Dict)
# Deleting the name
Dict.pop("name")
print(Dict)
π¨οΈ Output:
{'name': 'sujit', 'blog': 'fossguru', 'age': 30}
{'blog': 'fossguru', 'age': 30}
5.3. clear()
β The Clean Slateβ
Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}
print(Dict)
# Clear all the dictionary items
Dict.clear()
print(Dict)
π¨οΈ Output:
{'name': 'sujit', 'blog': 'fossguru', 'age': 30}
{}
6. π Iterating Over Dictionary Items β For Loop Party πβ
6.1. Classic for
Loopβ
Dict = {
"name":"sujit",
"blog":"fossguru",
"age":30
}
for k in Dict:
v = Dict[k]
print("Key :" + k + ", Value: " + str(v))
π¨οΈ Output:
Key :name, Value: sujit
Key :blog, Value: fossguru
Key :age, Value: 30
6.2. Values Only β values()
methodβ
Dict = {
"name":"sujit",
"blog":"fossguru"
}
for v in Dict.values():
print("Value :" + v)
π¨οΈ Output:
Value :sujit
Value :fossguru
6.3. Full Combo β items()
methodβ
Dict = {
"name":"sujit",
"blog":"fossguru"
}
for i in Dict.items():
print(i)
print("Key :" + i[0] + ", Value: " + i[1])
π¨οΈ Output:
('name', 'sujit')
Key :name, Value: sujit
('blog', 'fossguru')
Key :blog, Value: fossguru
7. π§ββοΈ Built-in Dictionary Magic Spells (a.k.a. Methods)β
Method | Description |
---|---|
clear() | Clears everything. Poof! |
copy() | Makes a clone, no evil twin. |
fromkeys() | Mass-produce keys with the same value. |
get() | Retrieves values gently. |
items() | Shows key-value pairs in a tuple outfit. |
keys() | Just the keys, please. |
pop() | Bye-bye specific key. |
popitem() | Bye-bye last item. |
setdefault() | Adds key if missing. |
update() | Updates or adds stuff. |
values() | Just the values, no strings attached. |
Examples? Coming right up πΏ:
Dict = {"name":"sujit", "blog":"fossguru"}
Dict.clear()
print(Dict)
{}
Dict = {"name":"sujit", "blog":"fossguru"}
myDict = Dict.copy()
print(myDict)
{'name': 'sujit', 'blog': 'fossguru'}
keys = ('key1', 'key2', 'key3')
value = 0
Dict = dict.fromkeys(keys, value)
print(Dict)
{'key1': 0, 'key2': 0, 'key3': 0}
Dict = {"name":"sujit", "blog":"fossguru"}
print(Dict.get("name"))
sujit
...and so on! Youβve got the power now π§ β‘
π Congrats! You're now officially a Python Dictionary Wizard! π§ββοΈπ